package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.base.BaseDialog;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.ApplyTransferBean;
import com.qiantu.api.entity.CreateSceneResult;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.entity.SettingBean;
import com.qiantu.api.entity.UserInfoBean;
import com.qiantu.api.http.HttpBaseData;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppFragment;
import com.qiantu.phone.event.DeviceDetailChangeEvent;
import com.qiantu.phone.event.LanModeChangeEvent;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.event.RefreshHomeDeviceSortSettingEvent;
import com.qiantu.phone.event.RefreshHomeWeatherSettingEvent;
import com.qiantu.phone.event.RefreshHouseEvent;
import com.qiantu.phone.event.RefreshPushBannerSettingEvent;
import com.qiantu.phone.event.RefreshSceneEvent;
import com.qiantu.phone.event.UpdateFavouriteEvent;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.adapter.NavigationAdapter;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.fragment.HomeNewFragment;
import com.qiantu.phone.ui.fragment.MineFragment;
import com.qiantu.phone.ui.fragment.RoomFragment;
import com.qiantu.phone.ui.fragment.SmartFragment;
import com.qiantu.phone.ui.fragment.TimeFragment;
import com.qiantu.phone.utils.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class HomeActivity extends AppActivity
        implements NavigationAdapter.OnNavigationListener {

    public static final String INTENT_KEY_IN_FRAGMENT_INDEX = "fragmentIndex";
    public static final String INTENT_KEY_IN_FRAGMENT_CLASS = "fragmentClass";
    public static final String INTENT_KEY_IN_IS_RESET = "isReset";

    private View mFragmentContainer;
    private RecyclerView mNavigationView;
    private View deviceViewContainer;
    private ViewGroup deviceItemLongClickContainer;
    private View line;
    private View userInfoLayout;
    private View emptyHouseLayout;
    private ImageView userIcon;
    private TextView tvNickname;

    private NavigationAdapter mNavigationAdapter;
    private TranslateAnimation mShowTranslateAnimation;
    private TranslateAnimation mHideTranslateAnimation;
    private HomeNewFragment mHomeFragment;
    private RoomFragment mRoomFragment;
    private AppFragment mSmartFragment;
    private AppFragment mTimeFragment;
    private AppFragment mMineFragment;
    private SparseArray<AppFragment> mFragments = new SparseArray<>();
    private int lastPosition = -1;
    private FrameLayout lanLayout;

    public static void start(Context context) {
        start(context, HomeNewFragment.class);
    }

    public static void start(Context context, Class<? extends AppFragment<?>> fragmentClass) {
        Intent intent = new Intent(context, HomeActivity.class);
        intent.putExtra(INTENT_KEY_IN_FRAGMENT_CLASS, fragmentClass);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_activity;
    }

    @Override
    protected void initView() {
        overridePendingTransition(R.anim.anim_fade_in, R.anim.anim_fade_out);
        EventBus.getDefault().register(this);
        mFragmentContainer = findViewById(R.id.fragment_container);
        mNavigationView = findViewById(R.id.rv_home_navigation);
        line = findViewById(R.id.line);
        userInfoLayout = findViewById(R.id.user_info_layout);
        emptyHouseLayout = findViewById(R.id.empty_house_layout);
        deviceViewContainer = findViewById(R.id.device_view_container);
        deviceItemLongClickContainer = findViewById(R.id.device_item_long_click_container);
        lanLayout = findViewById(R.id.home_lan_mode);
        setOnClickListener(deviceItemLongClickContainer);

        ImmersionBar.setTitleBar(this, userInfoLayout);
        setOnClickListener(R.id.btn_edit_user_info, R.id.btn_add_house, R.id.btn_scan_add, R.id.home_lan_mode);
        getUntreatedTransferList();
        updateView(true);
    }

    private void updateView(Boolean isOperpage) {
        if (userInfoLayout == null) {
            return;
        }
        lanLayout.setVisibility(HttpBaseData.getInstance().isLanMode() ? View.VISIBLE : View.GONE);
        if (AppApplication.getInstance().getCurHouseInfo() == null) {
            userInfoLayout.setVisibility(View.VISIBLE);
            emptyHouseLayout.setVisibility(View.VISIBLE);
            mFragmentContainer.setVisibility(View.GONE);
            mNavigationView.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
            userIcon = findViewById(R.id.user_icon);
            tvNickname = findViewById(R.id.tv_nickname);
            if (AppApplication.getInstance().getLoginInfo() != null) {
                UserInfoBean userInfoBean = AppApplication.getInstance().getLoginInfo().getUserInfo();
                if (userInfoBean == null) {
                    return;
                }
                GlideApp.with(getContext())
                        .load(userInfoBean.getAvatar())
                        .placeholder(userIcon.getDrawable())
                        .error(userIcon.getDrawable())
                        .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                        .into(userIcon);
                tvNickname.setText(userInfoBean.getNickName());
            }
        } else {
            AppApplication.getInstance().initSignalR();
            userInfoLayout.setVisibility(View.GONE);
            emptyHouseLayout.setVisibility(View.GONE);
            mFragmentContainer.setVisibility(View.VISIBLE);
            mNavigationView.setVisibility(View.VISIBLE);
            line.setVisibility(View.VISIBLE);
            if(mNavigationAdapter != null){
                mNavigationAdapter.clearData();
            }else{
                mNavigationAdapter = new NavigationAdapter(this);
            }
//            if(mNavigationAdapter == null){
            int[][] states = new int[2][];
            states[0] = new int[]{android.R.attr.state_selected};
            states[1] = new int[]{-android.R.attr.state_selected};
            StateListDrawable stateDrawable1 = new StateListDrawable();
            stateDrawable1.addState(states[0], AppApplication.getInstance().getThemeDrawable(R.attr.icon_menubar_home_on));
            stateDrawable1.addState(states[1], AppApplication.getInstance().getThemeDrawable(R.attr.icon_menubar_home_off));
            mNavigationAdapter.addItem(new NavigationAdapter.MenuItem(getString(R.string.homePage), stateDrawable1));
            StateListDrawable roomDrawable = new StateListDrawable();
            roomDrawable.addState(states[0], AppApplication.getInstance().getThemeDrawable(R.attr.icon_menubar_room_on));
            roomDrawable.addState(states[1], AppApplication.getInstance().getThemeDrawable(R.attr.icon_menubar_room_off));
            mNavigationAdapter.addItem(new NavigationAdapter.MenuItem(getString(R.string.home_nav_index), roomDrawable));
            if (AppApplication.getInstance().getCurHouseInfo().getRoleType() != 2) {
                StateListDrawable stateDrawable2 = new StateListDrawable();
                stateDrawable2.addState(states[0], AppApplication.getInstance().getThemeDrawable(R.attr.icon_menubar_intelligent_on));
                stateDrawable2.addState(states[1], AppApplication.getInstance().getThemeDrawable(R.attr.icon_menubar_intelligent_off));
                mNavigationAdapter.addItem(new NavigationAdapter.MenuItem(getString(R.string.intelligent), stateDrawable2));
//                StateListDrawable stateDrawable4 = new StateListDrawable();
//                stateDrawable4.addState(states[0], AppApplication.getInstance().getThemeDrawable(R.attr.icon_menubar_time_on));
//                stateDrawable4.addState(states[1], AppApplication.getInstance().getThemeDrawable(R.attr.icon_menubar_time_off));
//                mNavigationAdapter.addItem(new NavigationAdapter.MenuItem(getString(R.string.time), stateDrawable4));
            }

            StateListDrawable stateDrawable3 = new StateListDrawable();
            stateDrawable3.addState(states[0], AppApplication.getInstance().getThemeDrawable(R.attr.icon_menubar_me_on));
            stateDrawable3.addState(states[1], AppApplication.getInstance().getThemeDrawable(R.attr.icon_menubar_me_off));
            mNavigationAdapter.addItem(new NavigationAdapter.MenuItem(getString(R.string.home_nav_me), stateDrawable3));

            mNavigationView.setLayoutManager(new GridLayoutManager(this,mNavigationAdapter.getItemCount()));
            mNavigationAdapter.setOnNavigationListener(this);
            mNavigationView.setAdapter(mNavigationAdapter);

//            }

//            if (mFragmentManager == null) {
                mFragmentManager = getSupportFragmentManager();
                FragmentTransaction mTransaction = mFragmentManager.beginTransaction();
                mHomeFragment = (HomeNewFragment) mFragmentManager.findFragmentByTag(HomeNewFragment.class.getSimpleName());
                if (mHomeFragment == null) {
                    mHomeFragment = HomeNewFragment.newInstance();
                    //提前add，切换更流畅
                    mTransaction.add(R.id.fragment_container, mHomeFragment, mHomeFragment.getClass().getSimpleName());
                }
                mTransaction.hide(mHomeFragment);
                mRoomFragment = (RoomFragment) mFragmentManager.findFragmentByTag(RoomFragment.class.getSimpleName());
                if (mRoomFragment == null) {
                    mRoomFragment = new RoomFragment();
                    //提前add，切换更流畅
                    mTransaction.add(R.id.fragment_container, mRoomFragment, mRoomFragment.getClass().getSimpleName());
                }
                mTransaction.hide(mRoomFragment);
            if (AppApplication.getInstance().getCurHouseInfo().getRoleType() != 2) {
                mSmartFragment = (AppFragment) mFragmentManager.findFragmentByTag(SmartFragment.class.getSimpleName());
                if (mSmartFragment == null) {
                    mSmartFragment = new SmartFragment();
                    //提前add，切换更流畅
                    mTransaction.add(R.id.fragment_container, mSmartFragment, mSmartFragment.getClass().getSimpleName());
                }
                mTransaction.hide(mSmartFragment);
//                mTimeFragment = (AppFragment) mFragmentManager.findFragmentByTag(TimeFragment.class.getSimpleName());
//                if (mTimeFragment == null) {
//                    mTimeFragment = new TimeFragment();
//                    //提前add，切换更流畅
//                    mTransaction.add(R.id.fragment_container, mTimeFragment, mTimeFragment.getClass().getSimpleName());
//                }
//                mTransaction.hide(mTimeFragment);
            }

                mMineFragment = (AppFragment) mFragmentManager.findFragmentByTag(MineFragment.class.getSimpleName());
                if (mMineFragment == null) {
                    mMineFragment = MineFragment.newInstance();
                    //提前add，切换更流畅
                    mTransaction.add(R.id.fragment_container, mMineFragment, mMineFragment.getClass().getSimpleName());
                }
                mTransaction.hide(mMineFragment);
                mTransaction.commitNowAllowingStateLoss();
                mFragments.clear();
                mFragments.put(0, mRoomFragment);
                mFragments.put(1, mHomeFragment);
                if (AppApplication.getInstance().getCurHouseInfo().getRoleType() != 2) {
                    mFragments.put(2, mSmartFragment);
//                    mFragments.put(3, mTimeFragment);
                    mFragments.put(3, mMineFragment);
                } else {
                    mFragments.put(2, mMineFragment);
                }
//            }

            if(isOperpage){
                Integer key = SPUtils.getInstance().getInt("openpagedata");
                if (key == 1) {
                    switchFragment(1); // 常用页面现在是位置1
                } else if (key == 2) {
                    switchFragment(0); // 房间页面现在是位置0
                    mRoomFragment.setFirstShowType(0);
                } else if (key == 3) {
                    mRoomFragment.setFirstShowType(1);
                    switchFragment(0); // 房间页面现在是位置0
                } else if (key == 4) {
                    if (AppApplication.getInstance().getCurHouseInfo().getRoleType() == 2) {
                        switchFragment(1); // 常用页面现在是位置1
                    } else {
                        switchFragment(2);
                    }
                } else {
                    switchFragment(0); // 默认显示房间页面，现在是位置0
                }
            }else{
                switchFragment(lastPosition == -1 ? 0 : lastPosition); // 默认显示房间页面，现在是位置0
            }
        }
    }

    public HomeNewFragment getHomeFragment() {
        return mHomeFragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshHouseEvent(RefreshHouseEvent event) {
        updateView(false);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_edit_user_info:
                startActivity(PersonalDataActivity.class);
                break;
            case R.id.btn_add_house:
                FamilyInfoActivity.start(this, 1);
                break;
            case R.id.btn_scan_add:
                break;
            case R.id.device_item_long_click_container:
                hideLongClickFloatView();
                break;
            case R.id.home_lan_mode:
                SettingActivity.start(getContext());
                break;
        }
    }

    @Override
    protected void initData() {
        getAppSetting();
    }

    private void getAppSetting() {
        LLHttpManager.getAllSetting(new ApplicationLifecycle(), new HttpCallback<HttpData<SettingBean>>(null) {
            @Override
            public void onSucceed(HttpData<SettingBean> result) {
                AppApplication.getInstance().mSettingBean = result.getData();
                EventBus.getDefault().post(new RefreshHomeWeatherSettingEvent());
                EventBus.getDefault().post(new RefreshHomeDeviceSortSettingEvent());
                EventBus.getDefault().post(new RefreshPushBannerSettingEvent());
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //空房屋下更新用户信息
        if (userIcon != null && AppApplication.getInstance().getLoginInfo() != null) {
            UserInfoBean userInfoBean = AppApplication.getInstance().getLoginInfo().getUserInfo();
            if (userInfoBean == null) {
                return;
            }
            GlideApp.with(getContext())
                    .load(userInfoBean.getAvatar())
                    .placeholder(userIcon.getDrawable())
                    .error(userIcon.getDrawable())
                    .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                    .into(userIcon);
            tvNickname.setText(userInfoBean.getNickName());
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        boolean isReset = intent.getBooleanExtra(INTENT_KEY_IN_IS_RESET, false);
        if (isReset) {
            if (mHomeFragment != null) {
                mHomeFragment.initIndex();
            }
        }
        updateView(true);
        Class<? extends Fragment> fragmentClass = getSerializable(INTENT_KEY_IN_FRAGMENT_CLASS);
        if (fragmentClass != null) {
            int fragmentIndex = -1;
            for (int i = 0; i < mFragments.size(); i++) {
                if (fragmentClass.getName().equals(mFragments.get(i).getClass().getName())) {
                    fragmentIndex = i;
                }
            }
            switchFragment(fragmentIndex);
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        // 保存当前 Fragment 索引位置
//        outState.putInt(INTENT_KEY_IN_FRAGMENT_INDEX, mViewPager.getCurrentItem());
        outState.putInt(INTENT_KEY_IN_FRAGMENT_INDEX, lastPosition);
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        lastPosition = savedInstanceState.getInt(INTENT_KEY_IN_FRAGMENT_INDEX);
        // 恢复当前 Fragment 索引位置
        switchFragment(lastPosition);
    }

    private void switchFragment(int fragmentIndex) {
        if (AppApplication.getInstance().getCurHouseInfo() == null) {
            return;
        }
        if (fragmentIndex == -1) {
            return;
        }

        switch (fragmentIndex) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
//                mViewPager.setCurrentItem(fragmentIndex);
                selectItem(fragmentIndex);
                mNavigationAdapter.setSelectedPosition(fragmentIndex);
                break;
            default:
                break;
        }
    }

    /**
     * {@link NavigationAdapter.OnNavigationListener}
     */

    @Override
    public boolean onNavigationItemSelected(int position) {
        if (deviceItemLongClickContainer.getVisibility() == View.VISIBLE) {
            hideLongClickFloatView();
            return false;
        }
        switch (position) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
//                mViewPager.setCurrentItem(position);
                selectItem(position);
                return true;
            default:
                return false;
        }
    }

    private void selectItem(int position) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }
        FragmentTransaction mTransaction = mFragmentManager.beginTransaction();
//        if (lastPosition != -1) {
//            Log.i("lzx", "Fragment:" + mFragments.get(lastPosition));
//            mTransaction.hide(mFragments.get(lastPosition));
//        }
        for (int i = 0; i < mFragments.size(); i++) {
            int key = mFragments.keyAt(i);
            if (key != position) {
                Fragment f = mFragments.get(key);
                if (f.isAdded()) {
                    mTransaction.hide(f);
                }
            }
        }
        Fragment fragment = mFragments.get(position);
        if (fragment == null) {
            position = 0;
            fragment = mFragments.get(position);
        }
        if (fragment.isAdded()) {
            mTransaction.show(fragment);
        } else {
            Log.i("lzx", "fragment.getClass().getSimpleName():" + fragment.getClass().getSimpleName());
            mTransaction.add(R.id.fragment_container, fragment, fragment.getClass().getSimpleName());
        }
        // 事务提交
        mTransaction.commitNowAllowingStateLoss();
        lastPosition = position;
    }

    public void addRoom(View view) {
        Intent intent = new Intent(getContext(), AddRoomActivity.class);
        startActivity(intent);
    }

    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;

    public void logout(View view) {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setContent(getString(R.string.logout_hint));
        mConfirmCancelHintDialogBuilder.setRightText(R.string.logout);
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                AppApplication.getInstance().logoutToLogin();
            }
        });
        mConfirmCancelHintDialog.show();
    }

    public void longClickDeviceItem(int left, int top, int width, int height, DeviceBean device, boolean isFavourite) {
        if(AppApplication.getInstance().getCurHouseInfo().getRoleType() == 2){
            return;
        }
        deviceItemLongClickContainer.setVisibility(View.VISIBLE);
        deviceItemLongClickContainer.removeAllViews();
        int shadowSize = getResources().getDimensionPixelSize(R.dimen.dp_4);
        FrameLayout.LayoutParams fl = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        fl.leftMargin = left + shadowSize;
        fl.topMargin = top + shadowSize;
        fl.width = width - shadowSize * 2;
        fl.height = height - shadowSize * 2;
        View view;
//        //设备展开并且不是开关类型
//        if (device.isSwitch() && !SWITCH.stringType.equals(device.getDeviceType())) {
        if (device.getIsSwitch() && device.getHasCard() == 1) {//设备展开并且是可展开类型
            view = LayoutInflater.from(getContext()).inflate(R.layout.home_big_device_long_click_item, null, false);
        } else {
            view = LayoutInflater.from(getContext()).inflate(R.layout.home_device_long_click_item, null, false);
        }
        DeviceItemOnClickListener deviceItemOnClickListener = new DeviceItemOnClickListener(device, isFavourite);
        View btnSwitch = view.findViewById(R.id.btn_switch);
//        if (SWITCH.stringType.equals(device.getDeviceType())) {
        ImageView btnTopping = view.findViewById(R.id.btn_topping);
        btnTopping.setImageDrawable(AppApplication.getInstance().getDrawable(R.mipmap.icon_intelligent_sort_nocommon));
        if (device.getHasCard() == 0) {//不可展开类型
            btnSwitch.setVisibility(View.GONE);
        } else {
            btnSwitch.setVisibility(View.VISIBLE);
            btnSwitch.setOnClickListener(deviceItemOnClickListener);
        }
        view.findViewById(R.id.btn_topping).setOnClickListener(deviceItemOnClickListener);
        view.findViewById(R.id.btn_setting).setOnClickListener(deviceItemOnClickListener);
        deviceItemLongClickContainer.addView(view, fl);
    }

    public void longClickSceneItem(int left, int top, int width, int height, SceneBean scene, boolean isFavourite) {
        deviceItemLongClickContainer.setVisibility(View.VISIBLE);
        deviceItemLongClickContainer.removeAllViews();
        int shadowSize = getResources().getDimensionPixelSize(R.dimen.dp_4);
        FrameLayout.LayoutParams fl = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        fl.leftMargin = left + shadowSize;
        fl.topMargin = top + shadowSize;
        fl.width = width - shadowSize * 2;
        fl.height = height - shadowSize * 2;
        View view = LayoutInflater.from(getContext()).inflate(R.layout.home_scene_long_click_item, null, false);

        SceneItemOnClickListener sceneItemOnClickListener = new SceneItemOnClickListener(scene);
        view.findViewById(R.id.btn_topping).setVisibility(View.GONE);
        view.findViewById(R.id.btn_copy).setOnClickListener(sceneItemOnClickListener);
        deviceItemLongClickContainer.addView(view, fl);
    }

    private class DeviceItemOnClickListener implements View.OnClickListener {

        private DeviceBean mDevice;

        private boolean isFavourite;

        public DeviceItemOnClickListener(DeviceBean device, boolean isFavourite) {
            mDevice = device;
            this.isFavourite = isFavourite;
        }

        public void topDevice() {
            LLHttpManager.topDevice(HomeActivity.this, mDevice.getDeviceSerialNo(), true, 2, new HttpCallback<HttpData<Void>>(null) {
                @Override
                public void onStart(Call call) {
                    showDialog(getString(R.string.setting));
                }

                @Override
                public void onSucceed(HttpData<Void> result) {
                    LLDeviceDBManager.getInstance(getContext()).updateDeviceTop(2, mDevice.getDeviceSerialNo(), mDevice.getRoomSerialNo());
                    EventBus.getDefault().post(new RefreshDeviceListEvent(mDevice.getRoomSerialNo(), mDevice.getIsFavourite()));
                }

                @Override
                public void onFail(Exception e) {
                    toast(R.string.set_failed);
                }

                @Override
                public void onEnd(Call call) {
                    hideDialog();
                }
            });
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_topping:
                    if (mDevice.getIsFavourite()) {
                        if (mDevice.getDeviceGroup() == 0) {
                            topDevice();
                        }
                    } else {
                        Map<String, Object> data = new HashMap<>();
                        data.put("isFavourite", true);
                        List<String> selectedSerialNos = new ArrayList<>();
                        selectedSerialNos.add(mDevice.getDeviceSerialNo());
                        HttpCallback<HttpData<Void>> callback = new HttpCallback<HttpData<Void>>(null) {
                            @Override
                            public void onStart(Call call) {
                                showDialog(getString(R.string.setting));
                            }

                            @Override
                            public void onSucceed(HttpData<Void> result) {
                                if (result.isRequestSucceed()) {
                                    LLDeviceDBManager.getInstance(getContext()).updateDeviceFavourite(true, selectedSerialNos);
                                    //常用改变首页设备需要刷新
                                    EventBus.getDefault().post(new RefreshDeviceListEvent(mDevice.getRoomSerialNo(), true));
                                    EventBus.getDefault().post(new DeviceDetailChangeEvent(mDevice.getDeviceSerialNo()));
                                    //更新首页常用tab
                                    EventBus.getDefault().post(new UpdateFavouriteEvent(UpdateFavouriteEvent.TYPE_ADD));
                                    if (mDevice.getDeviceGroup() == 0) {
                                        topDevice();
                                    }
                                }
                            }

                            @Override
                            public void onFail(Exception e) {
                                toast(R.string.set_failed);
                            }

                            @Override
                            public void onEnd(Call call) {
                                hideDialog();
                            }
                        };
                        if (mDevice.getDeviceGroup() == 0) {
                            data.put("deviceSerialNoList", selectedSerialNos);
                            LLHttpManager.deviceIsFavourite(HomeActivity.this, data, callback);
                        } else {
                            data.put("deviceGroupSerialNos", selectedSerialNos);
                            LLHttpManager.deviceGroupIsFavourite(HomeActivity.this, data, callback);
                        }
                    }
                    break;
                case R.id.btn_switch:
                    HttpCallback<HttpData<Void>> callback = new HttpCallback<HttpData<Void>>(null) {
                        @Override
                        public void onStart(Call call) {
                            showDialog(getString(R.string.setting));
                        }

                        @Override
                        public void onSucceed(HttpData<Void> result) {
                            LLDeviceDBManager.getInstance(getContext()).updateExpand(mDevice.getDeviceSerialNo(), !mDevice.getIsSwitch());
                            EventBus.getDefault().post(new RefreshDeviceListEvent(mDevice.getRoomSerialNo(), mDevice.getIsFavourite()));
                        }

                        @Override
                        public void onFail(Exception e) {
                            toast(R.string.set_failed);
                        }

                        @Override
                        public void onEnd(Call call) {
                            hideDialog();
                        }
                    };
                    if (mDevice.getDeviceGroup() == 0) {
                        LLHttpManager.deviceIsSwitch(HomeActivity.this, mDevice.getDeviceSerialNo(), !mDevice.getIsSwitch(), callback);
                    } else {
                        LLHttpManager.groupDeviceIsSwitch(HomeActivity.this, mDevice.getDeviceSerialNo(), !mDevice.getIsSwitch(), callback);
                    }

                    break;
                case R.id.btn_setting:
                    if(AppApplication.getInstance().getCurHouseInfo().getRoleType() != 2) {
                        DeviceSettingActivity.start(getContext(), mDevice.getDeviceSerialNo(), true);
                    }
                    break;
            }
            hideLongClickFloatView();
        }
    }

    private class SceneItemOnClickListener implements View.OnClickListener {

        private SceneBean mScene;

        private boolean isFavourite;

        public SceneItemOnClickListener(SceneBean scene) {
            mScene = scene;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_copy:
                    LLHttpManager.copyScene(HomeActivity.this, mScene.getSceneSerialNo(), new HttpCallback<HttpData<CreateSceneResult>>(null) {
                        @Override
                        public void onStart(Call call) {
                            showDialog(getString(R.string.setting));
                        }

                        @Override
                        public void onSucceed(HttpData<CreateSceneResult> result) {
                            LLSceneDBManager.getInstance(getContext()).put(result.getData().getCreateSceneDto());
                            EventBus.getDefault().post(new RefreshSceneEvent());
                        }

                        @Override
                        public void onFail(Exception e) {
                            toast(R.string.set_failed);
                        }

                        @Override
                        public void onEnd(Call call) {
                            hideDialog();
                        }
                    });
                    break;
            }
            hideLongClickFloatView();
        }
    }

    public void hideLongClickFloatView() {
        if (deviceItemLongClickContainer.getVisibility() == View.GONE) {
            return;
        }
        deviceItemLongClickContainer.removeAllViews();
        deviceItemLongClickContainer.setVisibility(View.GONE);
    }

    private Fragment deviceFragment;
    private FragmentManager mFragmentManager;

    public void showDeviceView(View clickView, Fragment fragment) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (deviceFragment != null && deviceFragment.isAdded()) {
            transaction.remove(deviceFragment);
        }
        deviceFragment = mFragmentManager.findFragmentByTag("device_view");
        if (deviceFragment != null && deviceFragment.isAdded()) {
            transaction.remove(deviceFragment);
        }
        deviceFragment = fragment;
        transaction.add(R.id.device_view_container, fragment, "device_view");
        // 事务提交
        transaction.commitNowAllowingStateLoss();
        deviceViewContainer.setVisibility(View.VISIBLE);
        ViewGroup contentView = deviceViewContainer.findViewById(R.id.content_view);
        if (contentView.getChildCount() > 0) {
            View deviceView = contentView.getChildAt(0);
            showTopBottomAnimation(deviceView);
//            showScaleAnimation(clickView, deviceView);
        }
    }

    public boolean hideDeviceView() {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }
        deviceFragment = mFragmentManager.findFragmentByTag("device_view");
        if (deviceFragment != null) {
            ViewGroup contentView = deviceViewContainer.findViewById(R.id.content_view);
            if (contentView.getChildCount() > 0) {
                View deviceView = contentView.getChildAt(0);
                hideTopBottomAnimation(deviceView);
                return true;
            }
        }
        return false;
    }

    public void showSettingView(DeviceBean deviceBean) {
        if(AppApplication.getInstance().getCurHouseInfo().getRoleType() != 2) {
            DeviceSettingActivity.start(getContext(), deviceBean.getDeviceSerialNo(), false);
        }
    }

    private void showTopBottomAnimation(View deviceView) {
        if (mShowTranslateAnimation == null) {
            mShowTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0);
            mShowTranslateAnimation.setDuration(300);//跑一个周期所用时长
            mShowTranslateAnimation.setInterpolator(new FastOutSlowInInterpolator());
        }
        deviceView.setVisibility(View.VISIBLE);
        deviceView.startAnimation(mShowTranslateAnimation);
    }

    private void hideTopBottomAnimation(View deviceView) {
        if (mHideTranslateAnimation == null) {
            mHideTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1);
            mHideTranslateAnimation.setDuration(300);//跑一个周期所用时长
            mHideTranslateAnimation.setInterpolator(new FastOutSlowInInterpolator());
            mHideTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    FragmentTransaction transaction = mFragmentManager.beginTransaction();
                    if (deviceFragment != null && deviceFragment.isAdded()) {
                        transaction.remove(deviceFragment);
                    }
                    // 事务提交
                    transaction.commitNowAllowingStateLoss();
                    deviceViewContainer.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        deviceView.startAnimation(mHideTranslateAnimation);
    }


//    private int left;
//    private int top;
//    private int right;
//    private int bottom;
//    public void showDeviceView(View clickView, Fragment fragment){
//        if(mFragmentManager == null){
//            mFragmentManager = getSupportFragmentManager();
//        }
//        FragmentTransaction mTransaction = mFragmentManager.beginTransaction();
//        mTransaction.add(R.id.device_view_container, fragment,  "device_view");
//        // 事务提交
//        mTransaction.commitNowAllowingStateLoss();
//        deviceViewContainer.setVisibility(View.VISIBLE);
//
//        ViewGroup contentView = deviceViewContainer.findViewById(R.id.content_view);
//        if (contentView.getChildCount() > 0) {
//            View deviceView = contentView.getChildAt(0);
//            deviceView.post(new Runnable() {
//                @Override
//                public void run() {
//                    deviceView.setVisibility(View.VISIBLE);
//                    int[] clickViewLocation = new int[2];
//                    clickView.getLocationInWindow(clickViewLocation);
//                    int[] deviceViewLocation = new int[2];
//                    deviceView.getLocationInWindow(deviceViewLocation);
//                    int clickL = clickViewLocation[0];
//                    int clickT = clickViewLocation[1];
//                    int clickR = clickL + clickView.getWidth();
//                    int clickB = clickT + clickView.getHeight();
//
//                    int deviceL = deviceViewLocation[0];;
//                    int deviceT = deviceViewLocation[1];;
//                    int deviceR = deviceL + deviceView.getWidth();
//                    int deviceB = deviceT + deviceView.getHeight();
//
//                    left = clickL;
//                    top = clickT;
//                    right = clickR;
//                    bottom = clickB;
//                    ValueAnimator valueAnimatorL = new ValueAnimator();
//                    valueAnimatorL.setIntValues(clickL, deviceL);
//                    valueAnimatorL.setDuration(300);
//                    valueAnimatorL.setInterpolator(new LinearInterpolator());
//                    valueAnimatorL.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//                        @Override
//                        public void onAnimationUpdate(ValueAnimator animation) {
//                            left = (int) animation.getAnimatedValue();
//                            deviceView.layout(left, top, right, bottom);
//                        }
//                    });
//                    ValueAnimator valueAnimatorT = new ValueAnimator();
//                    valueAnimatorT.setIntValues(clickT, deviceT);
//                    valueAnimatorT.setDuration(300);
//                    valueAnimatorT.setInterpolator(new LinearInterpolator());
//                    valueAnimatorT.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//                        @Override
//                        public void onAnimationUpdate(ValueAnimator animation) {
//                            top = (int) animation.getAnimatedValue();
//                            deviceView.layout(left, top, right, bottom);
//                        }
//                    });
//                    ValueAnimator valueAnimatorR = new ValueAnimator();
//                    valueAnimatorR.setIntValues(clickR, deviceR);
//                    valueAnimatorR.setDuration(300);
//                    valueAnimatorR.setInterpolator(new LinearInterpolator());
//                    valueAnimatorR.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//                        @Override
//                        public void onAnimationUpdate(ValueAnimator animation) {
//                            right = (int) animation.getAnimatedValue();
//                            deviceView.layout(left, top, right, bottom);
//                        }
//                    });
//                    ValueAnimator valueAnimatorB = new ValueAnimator();
//                    valueAnimatorB.setIntValues(clickB, deviceB);
//                    valueAnimatorB.setDuration(300);
//                    valueAnimatorB.setInterpolator(new LinearInterpolator());
//                    valueAnimatorB.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//                        @Override
//                        public void onAnimationUpdate(ValueAnimator animation) {
//                            bottom = (int) animation.getAnimatedValue();
//                            deviceView.layout(left, top, right, bottom);
//                        }
//                    });
//                    AnimatorSet deviceViewAnimator = new AnimatorSet();
//                    deviceViewAnimator.playTogether(valueAnimatorL, valueAnimatorT, valueAnimatorR, valueAnimatorB);
//                    deviceViewAnimator.start();
//                }
//            });
//        }
//    }
//
//    public void hideDeviceView(){
//        FragmentManager fragmentManager = getSupportFragmentManager();
//        Fragment fragment = fragmentManager.findFragmentByTag("device_view");
//        if(fragment != null){
//            FragmentTransaction mTransaction = fragmentManager.beginTransaction();
//            if (fragment.isAdded()) {
//                mTransaction.remove(fragment);
//            }
//            // 事务提交
//            mTransaction.commitNowAllowingStateLoss();
//        }
//        deviceViewContainer.setVisibility(View.GONE);
//    }

    private void showScaleAnimation(View clickView, View deviceView) {
        deviceView.post(new Runnable() {
            @Override
            public void run() {
                deviceView.setVisibility(View.VISIBLE);
                int[] clickViewLocation = new int[2];
                clickView.getLocationInWindow(clickViewLocation);
                int clickViewL = clickViewLocation[0];
                int clickViewT = clickViewLocation[1];
                int clickViewR = clickView.getWidth() - clickViewL;
                int clickViewB = clickView.getHeight() - clickViewT;
                int[] deviceViewLocation = new int[2];
                deviceView.getLocationInWindow(deviceViewLocation);
                int deviceViewL = deviceViewLocation[0];
                int deviceViewT = deviceViewLocation[1];
                int deviceViewR = deviceView.getWidth() + deviceViewL;
                int deviceViewB = deviceView.getHeight() + deviceViewT;
                ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0, 1, Animation.ABSOLUTE, 200, Animation.ABSOLUTE, 500);
                scaleAnimation.setDuration(300);
                scaleAnimation.setInterpolator(new FastOutSlowInInterpolator());
                deviceView.setVisibility(View.VISIBLE);
                deviceView.startAnimation(scaleAnimation);
            }
        });
    }

    private void hideScaleAnimation(View clickView, View deviceView) {
        int[] clickViewLocation = new int[2];
        clickView.getLocationInWindow(clickViewLocation);
        int clickL = clickViewLocation[0];
        int clickT = clickViewLocation[1];
        int centerX = clickView.getWidth() - clickL;
        int centerY = clickView.getHeight() - clickT;
        if (mHideTranslateAnimation == null) {
            mHideTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.ABSOLUTE, 0, Animation.ABSOLUTE, 1);
            mHideTranslateAnimation.setDuration(300);//跑一个周期所用时长
            mHideTranslateAnimation.setInterpolator(new FastOutSlowInInterpolator());
            mHideTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    deviceViewContainer.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        deviceView.startAnimation(mHideTranslateAnimation);
    }

    @Override
    protected boolean isStatusBarDarkFont() {
        return AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont);
    }

    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        if (deviceItemLongClickContainer.getVisibility() == View.VISIBLE) {
            hideLongClickFloatView();
            return;
        }
        if (hideDeviceView()) {
            return;
        }
//        if (!DoubleClickHelper.isOnDoubleClick()) {
//            toast(R.string.home_exit_hint);
//            return;
//        }
//        // 移动到上一个任务栈，避免侧滑引起的不良反应
//        moveTaskToBack(false);
//        postDelayed(() -> {
//            // 进行内存优化，销毁掉所有的界面
//            ActivityManager.getInstance().finishAllActivities();
//            // 销毁进程（注意：调用此 API 可能导致当前 Activity onDestroy 方法无法正常回调）
//            // System.exit(0);
//        }, 300);

        if (System.currentTimeMillis() - exitTime > 2000) {
            toast(R.string.home_exit_hint);
            exitTime = System.currentTimeMillis();
        } else {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
        }
    }

    /**
     * 当用户没有收到过户的推送通知时，用户在打开APP时，APP需要主动查询当前用户的未处理的过户请求信息，并弹窗告知用户处理
     */
    private void getUntreatedTransferList() {
        LLHttpManager.getUntreatedTransferList(this, new HttpCallback<HttpData<List<ApplyTransferBean>>>(null) {
            @Override
            public void onSucceed(HttpData<List<ApplyTransferBean>> result) {
                if (result != null && result.getData() != null && result.getData().size() > 0) {
                    ApplyTransferBean applyTransferBean = result.getData().get(0);
                    AppApplication.getInstance().showTransferDialog(HomeActivity.this, applyTransferBean.getContent(), applyTransferBean.getTransferSerialNo(), applyTransferBean.getHouseSerialNo(), applyTransferBean.getCongratulations());
                }
            }

            @Override
            public void onFail(Exception e) {
            }

        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLanModeChangeEvent(LanModeChangeEvent event) {
        lanLayout.setVisibility(event.isLanMode ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (mViewPager != null) {
//            mViewPager.setAdapter(null);
//        }
        EventBus.getDefault().unregister(this);
        if (mNavigationView != null) {
            mNavigationView.setAdapter(null);
        }
        if (mNavigationAdapter != null) {
            mNavigationAdapter.setOnNavigationListener(null);
        }
    }
}